/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package evotingclient.controller;


import evotingclient.data.Card;
import evotingclient.data.Vote;
import evotingclient.model.Model;
import evotingclient.model.PersonalData;
import evotingclient.view.EVotingClientFrame;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLHandshakeException;
import javax.swing.JOptionPane;


/**
 *
 * @author Maciek
 */
public class Controller {
    
    
    String currentUserNick ;
    Model currentModel ;
    EVotingClientFrame view;
    
    public boolean createNewUser(String nick, String password, PersonalData pd){
        Model tempModel = Model.createNewModel(nick, password,pd);
        if(tempModel != null){
            currentUserNick = nick;
            currentModel = tempModel;
            return true;
        }
        else{
            System.out.println("Nie udało mi się stworzyć nowego użytkownika");
            return false;
        }
        
    }
    
    public boolean downloadPKWCert() throws Exception {
        System.out.println("Sciągam certyfikat pkw");
        // tu trzeba zmienic element który jest w sieci
        URL google = new URL("http://dl.dropbox.com/u/301664/uj/pkw.cer");
        ReadableByteChannel rbc = Channels.newChannel(google.openStream());
        FileOutputStream fos = new FileOutputStream(currentModel.getPath("PKW.cer"));
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        // sprawdzić czy na pewno się ściągnęło
        String cmd = "cmd.exe /c keytool -printcert -file ";
        cmd = cmd.concat(currentModel.getPath("PKW.cer"));
        Process process = Runtime.getRuntime().exec(cmd);
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        int retVal = process.waitFor();
        if(retVal == 0) {
            String line;
            StringBuilder certInfo = new StringBuilder();
            int lineCounter = 0;
            while((line = in.readLine()) != null) {
                lineCounter++;
                certInfo.append(line);
                certInfo.append("\n");
                if(lineCounter >= 10)
                    break;
            }
            
            int answer = JOptionPane.showConfirmDialog(null, 
                    certInfo.toString() + "\n\nCzy chcesz zaufać temu certyfikatowi?", 
                    "Zaufać certyfikatowi", JOptionPane.YES_NO_OPTION);
            if(answer == JOptionPane.YES_OPTION) {
                try {
                    this.currentModel.importCertificate();
                    // sukces
                    return true;
                } catch (IOException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return false;
    }
    
    public boolean exportCertificate(){
        try {
            //return this.currentModel.exportCertificate();
            return this.currentModel.requestSign();
        } catch (IOException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return false;
    }
    


    public void trustCertificate() {
        try {
            this.currentModel.importCertificate();
        } catch (IOException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void register() {
        this.currentModel.register();
    }

    

    public void getUser(String text, String jPasswordField3) {
        this.currentUserNick=text;
        this.currentModel = Model.getModel(text, jPasswordField3, null);
    }
    
    
    
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            //java.util.logging.Logger.getLogger(NotepadFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            //java.util.logging.Logger.getLogger(NotepadFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            //java.util.logging.Logger.getLogger(NotepadFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            //java.util.logging.Logger.getLogger(NotepadFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        final Controller controller = new Controller();
        
       java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                controller.view = new EVotingClientFrame(controller);
                controller.view.setVisible(true);
                
            }
       });
    }

    public String importSignedCertificate() {
        String info = null;
        try {
           int  retVal = this.currentModel.importSignedCertificate();
           if(retVal == 0){
            return "Certificate signed and imported successfully";
        }
        else{
            return "Importing and singing unsuccessfull";
        }   
        } catch(Exception ex){
            info = "We had a mistake " + ex.getMessage();
        }
        return info;
        
    }

    public void getCards() throws SSLHandshakeException, Exception {
        this.currentModel.getCards();
    }
    
    public Card readCard() {
        return this.currentModel.readCard();
    }

    public void sendVote(Vote v) {
        this.currentModel.sendVote(v);
    }
}
